package com.example.flashsales.controller;


import com.example.flashsales.entity.Result;
import com.example.flashsales.entity.dto.RefundDto;
import com.example.flashsales.entity.vo.MoneyVo;
import com.example.flashsales.entity.vo.OrdersVo;
import com.example.flashsales.entity.vo.ReturnOrderVo;
import com.example.flashsales.entity.vo.UserVo;
import com.example.flashsales.service.impl.OrderServiceImpl;
import com.example.flashsales.service.impl.RefundServiceImpl;
import com.example.flashsales.service.impl.UserCostRecordServiceImpl;
import com.example.flashsales.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Slf4j
@Controller
@RequestMapping("/userOrder")
public class UserOrderController {

    @Autowired
    UserCostRecordServiceImpl userCostRecordService;

    @Autowired
    UserServiceImpl userService;


    @Autowired
    OrderServiceImpl orderService;

    @Autowired
    RefundServiceImpl refundService;


    /**
     * 用户查看自己的订单
     *
     * @param httpServletRequest
     * @param page
     * @param num
     * @return
     */
    @ResponseBody
    @GetMapping("/viewOrders")
    public Result viewOrders(HttpServletRequest httpServletRequest,  Integer page,  Integer num) {
        if (page <= 0 || num < 0) {
            return Result.error("页数不能小于0");
        }
        long id = Integer.parseInt(httpServletRequest.getAttribute("id") + "");
        final Map<String, Object> map = userService.viewOrders(id, page, num);
        return Result.ok("查看成功").setData(map);

    }


    /**
     * 用户按时间查看订单
     *
     * @param qDate
     * @param hDate
     * @param page
     * @param num
     * @param httpServletRequest
     * @return
     */
    @GetMapping("/viewOrdersByTime")
    @ResponseBody
    public Result viewOrdersByTime(Date qDate, Date hDate, int page, int num, HttpServletRequest httpServletRequest) {
        if (page <= 0) {
            return Result.error("页数需要大于等于1");
        }
        long id = Integer.parseInt(httpServletRequest.getAttribute("id") + "");
        final Map<String, Object> map = userService.viewOrdersByTime(id, qDate, hDate, page, num);
        if (map.size() == 0){
            return Result.error("查看失败");
        }
        return Result.ok("查看成功").setData(map);
    }


    /**
     * 用户下单
     *
     * @param httpServletRequest
     * @param storeId
     * @return
     */
    @ResponseBody
    @GetMapping("/setOrder")
    public Result setOrder(HttpServletRequest httpServletRequest, long storeId) {
        long id = Integer.parseInt(httpServletRequest.getAttribute("id") + "");
        final MoneyVo v = userService.setOrder(id, storeId);
        if (v == null){
            return Result.error("下单失败");
        }
        return Result.ok("下单成功,请尽快支付").setData(v);

    }


    /**
     * 用户退单
     *
     * @param httpServletRequest
     * @param refundDto
     * @return
     */
    @ResponseBody
    @PostMapping("/refund")
    public Result refund(HttpServletRequest httpServletRequest, @RequestBody RefundDto refundDto) {
        final String refund = userService.refund(refundDto, refundDto.getRefundDetailsDtoList());
        if (refund.equals("提交成功")) {
            return Result.ok(refund);
        }
        return Result.error(refund);

    }


    /**
     * 查看用户的退单情况
     * @param refundId
     * @return
     */
    @ResponseBody
    @GetMapping("/viewRefundDetails")
    public Result viewRefundDetails(long refundId){
        final ReturnOrderVo returnOrderVo = userService.viewRefundDetails(refundId);
        if (returnOrderVo == null){
            return Result.error("查看失败");
        }
        return Result.ok("查看成功").setData(returnOrderVo);
    }


    /**
     * 用户查看自己的所有退款
     * @param httpServletRequest
     * @return
     */
    @ResponseBody
    @GetMapping("/viewAllRefund")
    public Result viewAllRefund(HttpServletRequest httpServletRequest){
        long id = Integer.parseInt(httpServletRequest.getAttribute("id") + "");
        final List<ReturnOrderVo> returnOrderVos = userService.viewAllRefund(id);
        return Result.ok("查看成功").setData(returnOrderVos);
    }


    /**
     * 按类型查看退款订单
     * @param httpServletRequest
     * @param state
     * @return
     */
    @ResponseBody
    @GetMapping("/viewRefundByState")
    public Result viewRefundByState(HttpServletRequest httpServletRequest,int state){
        long id = Integer.parseInt(httpServletRequest.getAttribute("id") + "");
        final List<ReturnOrderVo> returnOrderVos = userService.viewRefundByState(state, id);
        return Result.ok("查看成功").setData(returnOrderVos);
    }

    /**
     * 取消订单
     * @param orderId
     * @return
     */
    @ResponseBody
    @GetMapping("/deleteOrders")
    public Result deleteOrders(Long orderId){
        if (orderId == null){
            return Result.error("数据不能为空");
        }
        if (orderService.cancelOrder(orderId)) {
            return Result.ok("取消成功");
        }
        return Result.error("取消失败");
    }


    /**
     * 取消退款订单
     * @param refundId
     * @return
     */
    @ResponseBody
    @GetMapping("/deleteRefundOrder")
    public Result deleteRefundOrder(Long refundId){
        if (refundId == null){
            return Result.error("数据不能为空");
        }
        final ReturnOrderVo returnOrderVo = refundService.viewRefundDetails(refundId);
        if (returnOrderVo == null){
            return Result.error("退款订单不存在");
        }
        if (returnOrderVo.getState() != 0){
            return Result.error("改订单退款已经完成无法退款");
        }
        if (refundService.cancelRefundOrder(refundId) > 0) {
            return Result.ok("取消成功");
        }
        return Result.error("取消失败");
    }




    /**
     * 修改订单状态（支付宝）
     * @param httpServletResponse
     * @return
     * @throws IOException
     */
    @ResponseBody
    @GetMapping("/payByAliPay")
    public Result payByAliPay(HttpServletResponse httpServletResponse,HttpServletRequest httpServletRequest) throws IOException {
        log.info("支付宝支付成功");
        final String orderId = httpServletRequest.getParameter("orderId");
        final long id = Integer.parseInt(orderId);
        final OrdersVo ordersVo = orderService.viewOrder(id).get(0);
        final long userId = ordersVo.getUserId();
        if (orderService.updateMoneyAndMethod(id,1,ordersVo.getOrderMoney()) && orderService.updateOrderState(id,6)) {
//            修改订单状态成功
//            添加一条流水纪录
            if (userCostRecordService.addRecord(userId,id,ordersVo.getOrderMoney(),0,1)) {
//                httpServletResponse.sendRedirect("http://120.76.130.104:9000/index.html");
            }
        }
        httpServletResponse.sendRedirect("http://120.76.130.104:8080/index.html");
        return Result.ok();
    }

}
